package cn.shiro.shiroservice.auth.service.impl;

import cn.shiro.shiroservice.auth.pojo.dto.TokenManagerDTO;
import cn.shiro.shiroservice.auth.pojo.vo.in.LoginInVO;
import cn.shiro.shiroservice.auth.pojo.vo.out.UserInfoOutVo;
import cn.shiro.shiroservice.auth.provider.interfaces.impl.IAuthenticationTokenImpl;
import cn.shiro.shiroservice.auth.service.AccessCacheManager;
import cn.shiro.shiroservice.auth.service.AuthService;
import cn.shiro.shiroservice.auth.service.TokenManager;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * &#064;Time 2024 一月 星期一 09:50
 *
 * @author ShangGuan
 */
@Service
public class AuthServiceImpl implements AuthService {
    private final Logger log = LoggerFactory.getLogger(getClass());

    private final TokenManager tokenManager;

    private final AccessCacheManager<UserInfoOutVo> tokenCacheManger;
    private final RedisTemplate<String, Object> redisTemplate;


    @Autowired
    public AuthServiceImpl(RedisTemplate<String ,Object> redisTemplate) {
        this.tokenManager = new SimpleTokenManager(null);
        this.redisTemplate= redisTemplate;
        this.tokenCacheManger = new TokenCacheManger(this.redisTemplate);
    }

    @Override
    public UserInfoOutVo login(LoginInVO loginParam) {
        Subject subject = SecurityUtils.getSubject();
        AuthenticationToken simpleUserInfo = new IAuthenticationTokenImpl(loginParam.getUsername(), loginParam.getPassword());
        subject.login(simpleUserInfo);
        TokenManagerDTO accessTokenManager = tokenManager.generatesToken(loginParam.getUsername(),subject.getSession().getId().toString());
        UserInfoOutVo userInfoOutVo = new UserInfoOutVo(loginParam.getUsername(), accessTokenManager.getToken(), accessTokenManager.getExpireTime());
        tokenCache(userInfoOutVo.getUsername(), userInfoOutVo);
        return userInfoOutVo;
    }

    /**
     * 令牌缓存
     * @param username 用户名
     * @param obj      对象
     */
    protected void tokenCache(String username, UserInfoOutVo obj) {
        if (!tokenCacheManger.save(username, obj)) {
            log.warn("{}:缓存保存失败",getClass().toString());
        }
    }


    @Override
    public void saveUser() {

    }

    @Override
    public void deleteUser() {

    }

    @Override
    public void updateUser() {

    }
}
